<template>
  <div class="goods">
    <el-card class="box-card" v-if="status === 'index'">
      <el-row>
        <el-input v-model="searchParams.title" placeholder="请输入商品名称" clearable style="width:180px"
          size="mini"></el-input>
        <el-select v-model="searchParams.status" placeholder="请选择商品状态" clearable style="width:180px" size="mini">
          <el-option v-for="item in statusArr" :key="item.id" :value="item.id" :label="item.title"></el-option>
        </el-select>
        <el-select v-model="searchParams.cate" placeholder="请选择商品分类" clearable style="width:180px" size="mini">
          <el-option v-for="item in goodsCateArr" :key="item.id" :value="item.id" :label="item.title"></el-option>
        </el-select>
        <el-date-picker v-model="searchParams.startTime" type="date" data-format="" placeholder="选择起始时间" size="mini"
          style="width:150px"></el-date-picker>
        <el-date-picker v-model="searchParams.endTime" type="date" placeholder="选择结束时间" size="mini"
          style="width:150px"></el-date-picker>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getData"
          v-if="has('goods/index')">搜索</el-button>
        <el-button type="info" icon="el-icon-refresh" size="mini" @click="reset"
          v-if="has('goods/index')">重置</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="add" v-if="has('goods/store')">添加</el-button>
      </el-row>

      <el-table :data="data.data" v-loading="table_loading" style="width: 100%;margin:10px auto" size="mini"
        :header-cell-style="{ background: '#f3f8fe', color: '#333' }">
        <el-table-column fixed prop="id" label="ID" align="center"></el-table-column>
        <el-table-column prop="title" label="商品名" align="center"></el-table-column>
        <el-table-column label="商品主图" align="center">
          <template slot-scope="scope">
            <el-image :preview-src-list="[scope.row.image]" :src="scope.row.image" style="width: 100px; height: 100px"
              fit="contain"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="真实销量" align="center"></el-table-column>
        <el-table-column prop="price" label="价格" align="center"></el-table-column>
        <el-table-column label="商品分类" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-switch @change="changeStatus(scope.row)" v-model="scope.row.status" active-color="#13ce66"
              inactive-color="#ff4949" :active-value="activeValue" :inactive-value="inactiveValue">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" align="center"></el-table-column>

        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="edit(scope.row.id)" v-if="has('goods/show')">编辑</el-button>
            <el-button type="danger" size="mini" @click="del(scope.row.id, scope.$index)"
              v-if="has('goods/destroy')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background style="text-align:center;margin:20px 0;" :current-page="searchParams.page"
        :page-sizes="pageSizes" layout="total,prev, pager, next,sizes" :total="data.total" @size-change="changeSize"
        @current-change="changePage"></el-pagination>
    </el-card>
    <!-- 添加 -->
    <el-card v-if="status === 'add'">
      <div slot="header">
        <el-page-header @back="init" content="添加商品"></el-page-header>
      </div>
      <el-form ref="form" :rules="rules" :model="editParams" label-width="120px"
        :style="{ width: '90%', margin: '0 auto' }">
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="editParams.title" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="goods_cate_id">
          <el-select v-model="editParams.goods_cate_id" placeholder="请选择商品分类">
            <el-option v-for="item in goodsCateArr" :key="item.id" :value="item.id" :label="item.title"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品状态" prop="status">
          <el-select v-model="editParams.status">
            <el-option v-for="item in statusArr" :key="item.id" :value="item.id" :label="item.title"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="虚拟销量" prop="unreal_sales">
          <el-input v-model="editParams.unreal_sales" placeholder="显示销量=真实销量+虚拟销量"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="editParams.price" placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="商品轮播图" prop="goods_images">
          <el-button size="mini" type="primary" @click="openImage(1, true, extra)">选择商品库</el-button>
          <div class="goods_image" v-if="editParams.goods_images.length">
            <div class="image_box" v-for="(item, index) in editParams.goods_images" :key="index">
              <i class="el-icon-delete icon" @click="del_image(index)"></i>
              <img :src="item" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="封面图" prop="image">
          <el-button size="mini" type="primary" @click="openImage(2, false, extra)">选择商品库</el-button>
          <div>
            <el-image v-if="editParams.image" :src="editParams.image" :preview-src-list="[editParams.image]"
              style="height: 200px" fit="contain">
            </el-image>
          </div>
        </el-form-item>
        <!-- <el-form-item label="规格模式" prop="format">
          <el-radio-group v-model="editParams.format">
            <el-radio
              v-for="item in formatArr"
              :key="item.id"
              :label="item.id"
              >{{ item.title }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="商品规格" v-if="editParams.format == 2">
          <el-card>
            <el-row v-for="item in goodsAttrs" :key="item.id">
              <el-form-item :label="item.value">
                <el-checkbox :label="value.value" :value="value.is_checked" v-for="value in item.leaf" :key="value.id"
                  @change="changeCheck(value)"></el-checkbox>
              </el-form-item>
            </el-row>
          </el-card>
        </el-form-item>

        <el-form-item label="商品sku" v-if="editParams.format == 2">
          <el-button type="info" size="mini" disabled v-if="!skuStatus">请先选择商品规格</el-button>
          <el-table :data="goodsSkuArr" size="mini" border :header-cell-style="{ background: '#eee' }" v-if="skuStatus">
            <el-table-column :prop="item.prop" :label="item.label" align="center" v-for="item in cols"
              :key="item.id"></el-table-column>

            <el-table-column label="价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="兑换价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.exchange_price" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="销量" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sales" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="库存" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="图片" align="center">
              <template slot-scope="scope">
                <el-image v-if="scope.row.image" :src="scope.row.image" :preview-src-list="[scope.row.image]"
                  style="width: 100px; height: 100px" fit="contain">
                </el-image>
                <span v-else>未选择图片</span>
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" align="center" width="140">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="openImage(3, false, scope)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="商品详情" prop="content">
          <Editor v-model="editParams.content"></Editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('form', 1)">保 存</el-button>
          <el-button @click="init">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 编辑 -->
    <el-card v-if="status === 'edit'">
      <div slot="header">
        <el-page-header @back="init" content="编辑商品"></el-page-header>
      </div>
      <el-form ref="form" :rules="rules" :model="editParams" label-width="120px"
        :style="{ width: '90%', margin: '0 auto' }">
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="editParams.title" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="editParams.status" prop="status">
            <el-option v-for="item in statusArr" :key="item.id" :value="item.id" :label="item.title"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" placeholder="请选择商品分类" prop="goods_cate_id">
          <el-select v-model="editParams.goods_cate_id">
            <el-option v-for="item in goodsCateArr" :key="item.id" :value="item.id" :label="item.title"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="editParams.price" placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="虚拟销量" prop="unreal_sales">
          <el-input v-model="editParams.unreal_sales" placeholder="请输入虚拟销量"></el-input>
        </el-form-item>
        <el-form-item label="商品轮播图" prop="goods_images">
          <el-button size="mini" type="primary" @click="openImage(1, true, extra)">选择商品库</el-button>
          <div class="goods_image" v-if="editParams.goods_images.length">
            <div class="image_box" v-for="(item, index) in editParams.goods_images" :key="index">
              <i class="el-icon-delete icon" @click="del_image(index)"></i>
              <img :src="item.url" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="封面图" prop="image">
          <el-button size="mini" type="primary" @click="openImage(2, false, extra)">选择商品库</el-button>
          <div>
            <el-image v-if="editParams.image" :src="editParams.image" :preview-src-list="[editParams.image]"
              style="height: 200px" fit="contain">
            </el-image>
          </div>
        </el-form-item>
        <!-- <el-form-item label="规格模式" prop="format">
          <el-radio-group v-model="editParams.format" disabled>
            <el-radio
              v-for="item in formatArr"
              :key="item.id"
              :label="item.id"
              >{{ item.title }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="商品规格" v-if="editParams.format == 2">
          <el-card>
            <el-row v-for="item in goodsAttrs" :key="item.id">
              <el-form-item :label="item.value">
                <el-checkbox :label="value.value" :value="value.is_checked" v-for="value in item.leaf" :key="value.id"
                  @change="changeCheck(value)"></el-checkbox>
              </el-form-item>
            </el-row>
          </el-card>
        </el-form-item>

        <el-form-item label="商品sku" v-if="editParams.format == 2">
          <el-button type="info" size="mini" disabled v-if="!skuStatus">请先选择商品规格</el-button>
          <el-table :data="goodsSkuArr" border size="mini" :header-cell-style="{ background: '#f3f8fe', color: '#333' }"
            v-if="skuStatus">
            <el-table-column :prop="item.prop" :label="item.label" align="center" v-for="item in cols"
              :key="item.id"></el-table-column>

            <el-table-column label="价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="兑换价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.exchange_price" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="销量" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sales" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="库存" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="图片" align="center">
              <template slot-scope="scope">
                <el-image v-if="scope.row.image" :src="scope.row.image" :preview-src-list="[scope.row.image]"
                  style="width: 100px; height: 100px" fit="contain">
                </el-image>
                <span v-else>未选择图片</span>
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" align="center" width="140">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="openImage(3, false, scope)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="商品详情" prop="content">
          <Editor v-model="editParams.content"></Editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('form', 2)">保 存</el-button>
          <el-button @click="init">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <SimpleImageUpload :cardStatus="cardStatus" :imageFormatArr="imageFormatArr" :imageData="imageData"
      :imageLoading="imageLoading" :uploadImageAction="uploadImageUrl" :multiple="multiple"
      @uploadImageSuccess="uploadFileSuccess" @uploadImageBefore="uploadImageBefore" @changeImageSize="changeImageSize"
      @changeImagePage="changeImagePage" @changeImageFormat="changeImageFormat" @choiceImageConfirm="choiceImageConfirm"
      @closeImage="closeImage" @getImages="getImages"></SimpleImageUpload>
  </div>
</template>

<script>
import api from "../../api/api.js";
import { flatten, equal } from "../../utils/sku.js";
import SimpleImageUpload from "@/components/SimpleImageUpload/index.vue";
// 导入富文本
import Editor from "@/components/Editer/index.vue";
export default {
  components: {
    Editor,
    SimpleImageUpload
  },
  name: "goods",
  data() {
    return {
      status: "index", // 页面控制
      data: [], // 表格诗句
      table_loading: true, // 表格加载中
      loading: false, // 全局加载中
      activeValue: 1,
      inactiveValue: 0,
      skuStatus: false,
      uploadUrl: "localhost:8080", // 上传地址
      uploadImageUrl: "/admin/common/upload",
      goodsCateArr: [], // 商品分类
      statusArr: [
        { id: 0, title: "下架", color: "red" },
        { id: 1, title: "上架", color: "green" }
      ],
      formatArr: [
        { id: 1, title: "单规格" },
        { id: 2, title: "多规格" }
      ],
      pageSizes: [10, 20, 50, 100, 200, 500, 800, 1000, 2000], // 每页条数默认10
      searchParams: {
        // 搜索参数
        title: "",
        page: 1,
        limit: 10,
        startTime: "",
        endTime: "",
        status: "",
        cate: ""
      },
      editParams: {
        title: "",
        image: "",
        status: "",
        goods_images: [],
        goods_cate_id: "",
        content: "",
        unreal_sales: "",
        type: 2,
        format: 2,
        attrs: [], // 选择的属性和值
        sku: [] // sku
      },
      goodsAttrs: [], // 添加时查询出来的所有属性和值
      rules: {
        // 验证规则
        title: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        unreal_sales: [
          { required: true, message: "请输入商品销量", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择商品状态", trigger: "blur" }
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        goods_cate_id: [
          { required: true, message: "请选择商品分类", trigger: "change" }
        ],
        content: [
          { required: true, message: "请输入商品详情", trigger: "blur" }
        ],
        goods_images: [
          { required: true, message: "请上传商品轮播图", trigger: "blur" }
        ],
        image: [{ required: true, message: "请上传商品主图", trigger: "blur" }],
        format: [
          { required: true, message: "请选择商品规格模式", trigger: "blur" }
        ]
      },
      cardStatus: false,
      imageData: {},
      imageParams: {
        page: 1,
        limit: 50,
        format: ""
      },
      scene: 1, // 打开组件场景
      extra: {},
      multiple: true, // 默认组件多选
      imageFormatArr: [
        { id: "", title: "全部" },
        { id: 1, title: "商品图片" },
        { id: 2, title: "商品详情图" },
        { id: 3, title: "banner" },
        { id: 4, title: "活动" },
        { id: 5, title: "盲盒" }
      ],
      imageLoading: false
    };
  },
  created() {
    this.getData();
    this.getGoodsAttrs();
    this.getCate();
  },
  computed: {
    // 选择的商品属性和值
    attrs: function () {
      // 第一步 leaf is_checked
      return this.goodsAttrs
        .map(item => ({
          ...item,
          leaf: item.leaf.filter(value => {
            return value.is_checked === true;
          }) // 第二部 去掉空数组 lea
        }))
        .filter(item => {
          return item.leaf.length > 0;
        });
    },
    // 表格头(属性值不为空就显示属性)
    cols: function () {
      let temp = [];
      this.attrs.forEach(item => {
        temp.push({ prop: item.value, label: item.value });
      });
      return temp;
    },
    // sku表格内容(添加或编辑)
    goodsSkuArr: function () {
      let sku = flatten(this.attrs);
      // this.editParams.sku 编辑时查询出来的sku,isEqual 判断两个sku是否相等，相等替换掉算法生成的sku数据
      for (let j = 0; j < sku.length; j++) {
        let temp_sku = sku[j].skus;
        if (this.editParams.sku.length > 0) {
          for (let i = 0; i < this.editParams.sku.length; i++) {
            let equal1 = equal(
              JSON.parse(this.editParams.sku[i].attr_values),
              temp_sku
            );
            if (equal1) {
              sku[j].id = this.editParams.sku[i].id;
              sku[j].price = this.editParams.sku[i].price;
              sku[j].stock = this.editParams.sku[i].stock;
              sku[j].image = this.editParams.sku[i].image;
              sku[j].sales = this.editParams.sku[i].sales;
              sku[j].exchange_price = this.editParams.sku[i].exchange_price;
            }
          }
        }
      }

      // 转化成表格显示的数据格式
      let skuArr = [];
      for (let k = 0; k < sku.length; k++) {
        let obj = {};
        obj.id = sku[k].id;
        obj.price = sku[k].price;
        obj.image = sku[k].image;
        obj.exchange_price = sku[k].exchange_price;
        obj.stock = sku[k].stock;
        obj.sales = sku[k].sales;
        for (let i = 0; i < sku[k].skus.length; i++) {
          for (let key in sku[k].skus[i]) {
            if (key === "k") {
              obj[sku[k].skus[i][key]] = sku[k].skus[i].v;
            }
          }
        }
        skuArr.push(obj);
      }
      return skuArr;
    },

    // 返回给后端处理的数据(添加自定义字段 价格/图片/stock)
    skuArr: function () {
      let goodsAttrs = flatten(this.attrs);
      return goodsAttrs.map((value, key) => {
        this.goodsSkuArr.map((item, index) => {
          if (key === index) {
            value.id = item.id;
            value.price = item.price;
            value.sales = item.sales;
            value.image = item.image;
            value.stock = item.stock;
            value.exchange_price = item.exchange_price;
          }
        });
        return value;
      });
    }
  },
  methods: {
    changeStatus(e) {
      this.load();
      api.goods
        .status(e.id, { status: e.status })
        .then(res => {
          this.unload();
          if (res.data.code === 200) {
            this.$message.success("保存成功");
            this.init();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    uploadImageBefore() {
      this.load();
    },
    closeImage() {
      this.cardStatus = false;
    },
    // 改变图片组件每页条数时
    changeImageSize(limit) {
      this.imageParams.limit = limit;
      this.getImages();
    },
    // 改变图片组件当前页码时
    changeImagePage(page) {
      this.imageParams.page = page;
      this.getImages();
    },
    // 组件确定选择图片
    choiceImageConfirm(choiceImages) {
      console.log(choiceImages)
      if (this.scene == 1) {
        this.editParams.goods_images = this.editParams.goods_images.concat(
          choiceImages
        );
      } else if (this.scene == 2) {
        this.editParams.image = choiceImages[0];
      } else if (this.scene == 3) {
        this.extra.row.image = choiceImages[0];
      } else if (this.scene == 4) {
        var html = "";
        choiceImages.map(item => {
          html += `<div><img src="${item}" /></div>`;
        });
        this.setHtml(html);
        console.log("html:", html);
      }
    },
    // 组件图片上传成功取消遮罩重新请求数据
    uploadFileSuccess(res) {
      this.unload();
      this.getImages();
      this.$message.success(res.msg);
    },
    // 选择类型筛选图片
    changeImageFormat(type) {
      this.initImage(type);
      this.getImages();
    },
    // 重置图片搜索参数
    initImage(type) {
      this.imageParams.format = type;
      this.imageParams.page = 1;
    },
    // 查看图片
    getImages() {
      this.cardStatus = true;
      this.imageLoading = true;
      api.images
        .index({ params: this.imageParams })
        .then(res => {
          this.imageLoading = false;
          if (res.data.code == 200) {
            this.imageData = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    del_image(index) {
      this.$confirm("确定删除图片吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      })
        .then(() => {
          this.editParams.goods_images.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 查看大图
    bigImage(url) {
      this.$alert("图片", {
        message: "<img  src=" + url + " style='height:200px;width:200px'>",
        dangerouslyUseHTMLString: true
      });
    },
    getCate() {
      api.common.goodsCate().then(res => {
        if (res.data.code === 200) {
          this.goodsCateArr = res.data.data;
        }
      });
    },
    // 打开组件图片
    openImage(scene, multiple, extra) {
      this.multiple = multiple; // 单选还是多选
      this.scene = scene;
      this.extra = extra; // 额外数据
      this.cardStatus = true;
      this.getImages();
    },
    // 选择属性时
    changeCheck(value) {
      value.is_checked = !value.is_checked; // 状态取反
      this.skuStatus = this.attrs.length > 0;
    },
    // 加载中
    load() {
      this.loading = this.$loading({
        lock: true,
        text: "数据加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    // 取消加载
    unload() {
      this.loading.close();
    },
    // 获取所有商品
    getData() {
      this.table_loading = true;
      api.goods
        .index({ params: this.searchParams })
        .then(res => {
          if (res.data.code === 200) {
            this.table_loading = false;
            this.data = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 重置搜索参数重新搜索
    reset() {
      this.init();
      this.getData();
    },
    // 初始化
    init() {
      this.searchParams.title = "";
      this.searchParams.startTime = "";
      this.searchParams.endTime = "";
      this.searchParams.status = "";
      this.searchParams.cate = "";
      this.editParams = {
        // 添加/编辑参数
        title: "",
        image: "",
        status: "",
        goods_images: [],
        goods_cate_id: "",
        content: "",
        unreal_sales: "",
        type: 2,
        format: 2,
        attrs: [],
        status: 1,
        sku: []
      };
      this.status = "index";
      this.skuStatus = false;
      this.getGoodsAttrs();
    },
    // 改变每页条数时
    changeSize(limit) {
      this.searchParams.limit = limit;
      this.getData();
    },
    // 改变当前页码时
    changePage(page) {
      this.searchParams.page = page;
      this.getData();
    },
    // 查询属性和值(添加的时候)
    getGoodsAttrs() {
      api.common
        .goodsAttrs()
        .then(res => {
          if (res.data.code === 200) {
            this.goodsAttrs = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 添加页面
    add() {
      this.status = "add";
    },
    // 编辑页面
    edit(id) {
      this.load();
      api.goods
        .show(id)
        .then(res => {
          this.unload();
          if (res.data.code === 200) {
            this.editParams = res.data.data;

            this.skuStatus = true;
            let value_ids = []; // 所有的属性值id
            this.editParams.goods_attr_values.forEach(value => {
              value_ids.push(value.goods_value_id);
            });
            // 将选择的属性和值合并显示
            this.goodsAttrs.map(item => {
              return item.leaf.map(value => {
                if (value_ids.includes(value.id)) {
                  value.is_checked = true;
                }
              });
            });
            this.status = "edit";
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 保存添加或编辑
    submit(formName, type) {
      // 自动验证
      this.$refs[formName].validate((valid, error) => {
        if (valid) {
          if (this.editParams.format == 2) {
            this.editParams.skus = this.skuArr; // 为了避免影响计算属性 goodsSkuArr 使用 skus 而不是 sku
            this.editParams.attrs = this.attrs; // 选择的商品属性和值
            if (!this.editParams.attrs.length || !this.editParams.skus.length) {
              this.$message.error("请选择商品规格");
              return false;
            }
            for (let i = 0; i < this.editParams.skus.length; i++) {
              if (!this.editParams.skus[i].price) {
                this.$message.error("请输入价格");
                return false;
              }
              if (this.editParams.skus[i].stock < 0) {
                this.$message.error("请输入库存");
                return false;
              }
              if (
                !this.editParams.skus[i].sales &&
                this.editParams.skus[i].sales != 0
              ) {
                this.$message.error("请输入销量");
                return false;
              }
              if (!this.editParams.skus[i].image) {
                this.$message.error("请上传规格图片");
                return false;
              }
            }
          }
          this.load();
          if (type === 1) {
            api.goods
              .store(this.editParams)
              .then(res => {
                this.unload();
                if (res.data.code === 200) {
                  this.$message.success(res.data.msg);
                  this.reset();
                }
              })
              .catch(error => {
                console.log(error);
              });
          } else if (type === 2) {
            api.goods
              .edit(this.editParams.id, this.editParams)
              .then(res => {
                this.unload();
                if (res.data.code === 200) {
                  this.$message.success(res.data.msg);
                  this.reset();
                }
              })
              .catch(error => {
                console.log(error);
              });
          }
        } else {
          this.$message.error(Object.values(error)[0][0].message);
          return false;
        }
      });
    },
    // 删除
    del(id, index) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      })
        .then(() => {
          api.goods
            .del(id)
            .then(res => {
              if (res.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.data.data.splice(index, 1);
                this.data.total--;
              }
            })
            .catch(error => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style scoped lang="less">
.goods {
  margin: 0 auto;

  .search {
    margin: 0 auto 10px auto;
  }

  .img_box {
    display: flex;
    align-items: center;
    justify-content: space-around;

    img {
      width: 60px;
      height: 60px;
      cursor: pointer;
    }
  }
}

.goods_image {
  display: flex;
  flex-wrap: wrap;

  .image_box {
    margin: 10px;
    width: 200px;
    height: 200px;
    position: relative;

    img {
      width: 100%;
      height: 100%;
    }

    .icon {
      position: absolute;
      top: 10px;
      right: 10px;
      color: red;
      cursor: pointer;
    }
  }
}
</style>
